<?php

namespace App\Http\Controllers\Admin;
use App\DTOS\Admin\UserRoleDTO;
use App\Http\Controllers\Controller;
use App\Models\Game\CashMonitor;
use App\Models\Game\CashMonitorList;
use App\Models\Game\Equip;
use App\Models\Game\OperType;
use App\Models\Game\Server;
use App\Services\Game\UserMemberService;
use App\Services\Game\UserRoleService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;

class EquipmentController extends Controller
{
    private Request $request;
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    /**
     * EquipmentController constructor.
     * @param Request $request
     * @param UserRoleService $userRoleService
     * @param UserMemberService $userMemberService
     */
    public function __construct(Request $request, UserRoleService $userRoleService, UserMemberService $userMemberService)
    {
        $this->request = $request;
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }


    /**
     * @return array
     */
    private function buildData()
    {
        $searchData = $this->request->all();
        $itemName = data_get($searchData,'itemName');
        $roleName = data_get($searchData,'roleName');
        $opTypes = data_get($searchData,'opTypes');
        $itemUid= data_get($searchData,'itemUid');
        $page= data_get($searchData,'page');

        global $gameArea;
        if ($itemUid){
            $searchData['itemUid'] = $itemUid;
        }
        if ($opTypes) {
            $opTypes = explode(',',$opTypes);
            foreach($opTypes as &$opType){
                $opType = (int)$opType;
            }
            $searchData['opTypes'] = $opTypes;
        }
        if ($itemName){
            $itemIds = Equip::query()->where('name','like',"%$itemName%")->pluck('id')->toArray();
            if (!$itemIds) {
                throw new \Exception("没有数据.");
            }
            $searchData['itemIds'] = $itemIds;
        }
        if ($roleName){
            $gameRoleDTO = new UserRoleDTO(['nick'=>$roleName]);
            $userRolePaginate = $this->userRoleService->paginate($gameRoleDTO);
            if (empty($userRolePaginate->items())){
                throw new \Exception("没有数据..");
            }
            $roleIds = collect($userRolePaginate->items())->pluck('id')->unique()->toArray();
            $searchData['roleIds'] = $roleIds;
        }


        $res = callRpc("/Equipment3dService/paginate",$searchData,['gameArea'=>$gameArea]);
        MyLog::info('数据的长度'.json_encode(count($res['data'])));
        $res['page']=$page;
        if (empty($res['data'])){
            throw new \Exception("没有数据...");
        }

        return $res;
    }



    public function monitorpaginate()
    {
        //获取配置表信息
        $cashMonitor = CashMonitor::query()->get()->toArray();
        $model = CashMonitorList::query();
        $page = request()->get('page',1);
        $pageSize = request()->get('limit',20);
        $gameArea = request()->get('gameArea');
        $roleName = request()->get('roleName');
        $itemName = request()->get('itemName');
        $itemId = request()->get('itemId');
        $roleId = request()->get('roleId');
        $opTypes = request()->get('opTypes');
        $createDateTimeBegin = request()->get('createDateBegin');
        $createDateTimeEnd = request()->get('createDateEnd');
        if ($createDateTimeBegin){
            $model->where("nowdata",">=",$createDateTimeBegin);
        }
        if ($createDateTimeEnd){
            $model->where("nowdata","<=",$createDateTimeEnd);
        }
        if($roleName){
            $model->where('name',$roleName);
        }
        if($gameArea){
            $model->where('gameArea',$gameArea);
        }
        if($itemName){
            $model->where('equipName',$itemName);
        }
        if($itemId){
            $model->where('itemId',$itemId);
        }
        if($roleId){
            $model->where('roleId',$roleId);
        }
        if ($opTypes!==null){
            // 如果是字符串，拆分为数组
            if (is_string($opTypes)) {
                $opTypesArray = explode(',', $opTypes); // 将字符串拆分为数组
            } else {
                $opTypesArray = [$opTypes]; // 如果是单个值，放入数组
            }
            MyLog::info('选择的交易类型'.json_encode($opTypesArray));
            $model->whereIn('opType',$opTypesArray);
        }
        $paginate = $model->orderByDesc('points')->paginate($pageSize,'*','page',$page);
        $data = $paginate->items();
        $res = [];
        $res['code'] = 0;
        $res['count'] = $paginate->total();
        $res['data'] = $data;
        return ResponseUtil::json($res);
    }





    public function paginate()
    {
        try {
            $res = $this->buildData();
            return ResponseUtil::json($res);
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function kcpaginate()
    {
        try {
            $input = request()->only(['gameArea','itemId','page','limit']);
            $area = (int) data_get($input,'gameArea',0);
            $itemId = (string) data_get($input,'itemId');
            $page = (int) data_get($input,'page',1);
            $limit = (int) data_get($input,'limit',15);

            if (empty($itemId)){
                return ResponseUtil::json(['code'=>0,'count'=>0,'data'=>[]]);
            }

            // 切换区服数据库
            global $gameArea; $gameArea = $area;

            // 道具名称映射
            $equipName = Equip::query()->where('id',$itemId)->value('name');

            // 仅查询必要字段
            $roles = \App\Models\Game\UserRole::query()
                ->select(['id','nick','memid','bag','money'])
                ->get();

            $rows = [];
            $sumCount = 0; // 所有角色拥有该道具的总数量
            foreach ($roles as $role){
                $bag = data_get($role,'bag',[]);
                $list = data_get($bag,'list',[]);
                if (!is_array($list)) { continue; }

                $totalCount = 0;
                $money = $role->money;

                if (in_array($itemId, ['10', '20', '21'])) {
                    switch ($itemId) {
                        case '10':
                            $totalCount = (int)($money['gold'] ?? 0);
                            break;
                        case '20':
                            $totalCount = (int)($money['silver'] ?? 0);
                            break;
                        case '21':
                            $totalCount = (int)($money['copper'] ?? 0);
                            break;
                        default:
                            break;
                    }

                }else{
                    foreach ($list as $item){
                        // 兼容多种结构：data.id / data.ID / id / ID
                        $id = (string) (
                            data_get($item, 'data.id') ??
                            data_get($item, 'data.ID') ??
                            data_get($item, 'id') ??
                            data_get($item, 'ID') ??
                            ''
                        );
                        // 兼容数量字段：data.count / data.num / count / num
                        $countRaw = (
                            data_get($item, 'data.count') ??
                            data_get($item, 'data.num') ??
                            data_get($item, 'count') ??
                            data_get($item, 'num') ??
                            0
                        );
                        $count = (int) $countRaw;
                        if ($id === (string)$itemId){
                            $totalCount += $count;
                        }
                    }

                }




                if ($totalCount > 0){
                    $sumCount += $totalCount;
                    $rows[] = [
                        'logDate' => null,
                        'serverId' => $area,
                        'memId' => $role->memid,
                        'memberName' => '',
                        'roleId' => $role->id,
                        'nick' => $role->nick,
                        'itemId' => $itemId,
                        'equipName' => $equipName,
                        'countBefore' => $totalCount,
                    ];
                }
            }

            // 按数量倒序
            usort($rows, function($a,$b){ return ($b['countBefore'] <=> $a['countBefore']); });

            $total = count($rows);
            $offset = max(0, ($page - 1) * $limit);
            $data = array_slice($rows, $offset, $limit);

            $res = [];
            $res['code'] = 0;
            $res['count'] = $total;
            $res['data'] = $data;
            $res['sumCount'] = $sumCount;
            return ResponseUtil::json($res);
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function monitorexport() { //返利监控导出
        try {
            $model = CashMonitorList::query();
            $page = request()->get('page',1);
            $pageSize = request()->get('limit',20);
            $gameArea = request()->get('gameArea');
            $roleName = request()->get('roleName');
            $itemName = request()->get('itemName');
            $itemId = request()->get('itemId');
            $roleId = request()->get('roleId');
            $opTypes = request()->get('opTypes');
            $createDateTimeBegin = request()->get('createDateBegin');
            $createDateTimeEnd = request()->get('createDateEnd');
            if ($createDateTimeBegin){
                $model->where("nowdata",">=",$createDateTimeBegin);
            }
            if ($createDateTimeEnd){
                $model->where("nowdata","<=",$createDateTimeEnd);
            }
            if($roleName){
                $model->where('name',$roleName);
            }
            if($gameArea){
                $model->where('gameArea',$gameArea);
            }
            if($itemName){
                $model->where('equipName',$itemName);
            }
            if($itemId){
                $model->where('itemId',$itemId);
            }
            if($roleId){
                $model->where('roleId',$roleId);
            }
            if ($opTypes!==null){
                // 如果是字符串，拆分为数组
                if (is_string($opTypes)) {
                    $opTypesArray = explode(',', $opTypes); // 将字符串拆分为数组
                } else {
                    $opTypesArray = [$opTypes]; // 如果是单个值，放入数组
                }
                MyLog::info('选择的交易类型'.json_encode($opTypesArray));
                $model->whereIn('opType',$opTypesArray);
            }
            $paginate = $model->orderByDesc('points')->paginate($pageSize,'*','page',$page);
            $data = $paginate->items();

            $excelRows = [
                ['记录时间','物品名称','服务器ID','角色ID','角色名','操作类型','当前计数','物品ID']
            ];
            $opTypeList = OperType::query()->get()->toArray();

            foreach($data as $datum){
                if($datum['opTypeName'] ==null){
                    $datum['opTypeName']= getOpTypeName($opTypeList,$datum['opType']);
                }
                $excelRows[] = [
                    $datum['logDate'] ?? null,
                    $datum['equipName'] ?? null,
                    $datum['gameArea'] ?? null,
                    $datum['roleId'] ?? null,
                    $datum['nick'] ?? null,
                    $datum['opTypeName'] ?? null,
                    $datum['points'] ?? null,
                    $datum['itemId'] ?? null,

                ];
            }
           return ResponseUtil::success(cacheDownload(arrayToScvContent($excelRows),'.监控物品日志.csv'));
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }


    public function export() { //导出
        try {
            $res = $this->buildData();
            $totalCount = $res['count']; // 获取总条数
            MyLog::info('满足条件总书记数据的长度'.json_encode($totalCount));

            $excelRows = [
                ['记录时间','服务器ID','账号','角色ID','角色名','物品ID','物品名称','物品唯一ID','变化前','变化后','变动数','来源','去向','道具类型','操作类型','操作类型ID']
            ];
            $opTypeList = OperType::query()->get()->toArray();

            foreach($res['data'] as $datum){
                if($datum['opTypeName'] ==null){
                    $datum['opTypeName']= getOpTypeName($opTypeList,$datum['opType']);
                }
                $excelRows[] = [
                    $datum['logDate'] ?? null,
                    $datum['serverId'] ?? null,
                    $datum['memberName'] ?? null,
                    $datum['roleId'] ?? null,
                    $datum['nick'] ?? null,
                    $datum['itemId'] ?? null,
                    $datum['equipName'] ?? null,
                    "'" . ($datum['itemUid'] ?? null),
                    $datum['countBefore'] ?? null,
                    $datum['countAfter'] ?? null,
                    $datum['countChanged'] ?? null,
                    $datum['sourceName'] ?? null,
                    $datum['targetName'] ?? null,
                    $datum['getOrLostName'] ?? null,
                    $datum['opTypeName'] ?? null,
                    $datum['opType'] ?? null,

                ];
            }
            // 这里可以生成 CSV 文件
            $filePath = cacheDownload(arrayToScvContent($excelRows), '.物品日志_' . $res['page'] . '.csv');
            MyLog::info('下载链接'.json_encode($filePath).'所查拘束总数'.json_encode($totalCount));
            return ResponseUtil::success(['data' => $filePath, 'total' => $totalCount]);
        } catch (\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

}
